package com.caidan.security.service.impl;
import com.caidan.security.domain.dto.LoginParams;
import com.caidan.security.domain.entity.UmsSysUser;
import com.caidan.security.service.IUmsSysUser;
import com.caidan.security.web.JwtUtils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.stereotype.Service;

import java.util.HashMap;
import java.util.Map;
import java.util.UUID;

@Service
@Slf4j

public class UmsSysUserServiceImpl implements IUmsSysUser {

    private AuthenticationManager authenticationManager;

    public UmsSysUserServiceImpl(AuthenticationManager authenticationManager) {
        this.authenticationManager = authenticationManager;
    }
    @Autowired

    private JwtUtils jwtUtils;

    @Override
    public String login(LoginParams loginParams) {

        log.info("传入的用户信息是{}",loginParams);
//      传入 用户名和密码
        UsernamePasswordAuthenticationToken usernamePasswordAuthenticationToken =
                new UsernamePasswordAuthenticationToken
                        (loginParams.getUsername(), loginParams.getPassword());

//        实现登录逻辑 此时回去掉i用 loadUserByUsername方法

//        返回的Authentication 其实就是UserDeatils
        Authentication authenticate = null;
        try {
            authenticate = authenticationManager
                    .authenticate(usernamePasswordAuthenticationToken);
        }catch (Exception e){
            log.error("用户名或密码错误");
            return "用户名或密码错误";
        }
        UmsSysUser principal =
                (UmsSysUser) authenticate.getPrincipal();
        log.info("开始执行uuid");
//        String token = UUID.randomUUID().toString().replaceAll("-", "");

        Map map = new HashMap();
        map.put("name",loginParams.getUsername());
        String token = jwtUtils.createToken(map);
        log.warn("执行到这个位置输出的内容是{}",token);
        return token;
    }
}
